{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "import onnx\n",
    "from onnx import helper, shape_inference\n",
    "from onnx import TensorProto\n",
    "import onnx.optimizer"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Building a FC model for MNIST"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "import numpy as np\n",
    "import scipy.stats as stats\n",
    "\n",
    "def truncated_normal(dims):   \n",
    "    dim0, dim1 = dims\n",
    "    mu, stddev = 0, 1/math.sqrt(dim0)\n",
    "    lower, upper = -2 * stddev, 2 * stddev\n",
    "    X = stats.truncnorm( (lower - mu) / stddev, (upper - mu) / stddev, loc = mu, scale = stddev)\n",
    "\n",
    "    return X.rvs(dim0 * dim1).tolist()\n",
    "\n",
    "def zeros(dim):\n",
    "    return [0] * dim[0]\n",
    "   "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "W1_dims = [784, 128]\n",
    "W2_dims = [128, 32]\n",
    "W3_dims = [32, 10]\n",
    "\n",
    "W1 =  onnx.helper.make_tensor(name=\"W1\", data_type=onnx.TensorProto.FLOAT, dims=W1_dims, vals=truncated_normal(W1_dims))\n",
    "W2 =  helper.make_tensor(name=\"W2\", data_type=onnx.TensorProto.FLOAT, dims=W2_dims, vals=truncated_normal(W2_dims))\n",
    "W3 =  helper.make_tensor(name=\"W3\", data_type=onnx.TensorProto.FLOAT, dims=W3_dims, vals=truncated_normal(W3_dims))\n",
    "\n",
    "B1_dims = [128]\n",
    "B2_dims = [32]\n",
    "B3_dims = [10]\n",
    "\n",
    "B1 =  helper.make_tensor(name=\"B1\", data_type=onnx.TensorProto.FLOAT, dims=B1_dims, vals=zeros(B1_dims))\n",
    "B2 =  helper.make_tensor(name=\"B2\", data_type=onnx.TensorProto.FLOAT, dims=B2_dims, vals=zeros(B2_dims))\n",
    "B3 =  helper.make_tensor(name=\"B3\", data_type=onnx.TensorProto.FLOAT, dims=B3_dims, vals=zeros(B3_dims))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "node1 = helper.make_node('MatMul', inputs=['X', 'W1'], outputs=['T1'])\n",
    "node2 = helper.make_node('Add', inputs=['T1', 'B1'], outputs=['T2'])\n",
    "node3 = helper.make_node('Relu', inputs=['T2'], outputs=['T3'])\n",
    "\n",
    "node4 = helper.make_node('MatMul', inputs=['T3', 'W2'], outputs=['T4'])\n",
    "node5 = helper.make_node('Add', inputs=['T4', 'B2'], outputs=['T5'])\n",
    "node6 = helper.make_node('Relu', inputs=['T5'], outputs=['T6'])\n",
    "\n",
    "node7 = helper.make_node('MatMul', inputs=['T6', 'W3'], outputs=['T7'])\n",
    "node8 = helper.make_node('Add', inputs=['T7', 'B3'], outputs=['predictions'])\n",
    "\n",
    "graph = helper.make_graph(\n",
    "    [node1, node2, node3, node4, node5, node6, node7, node8],\n",
    "    'fully_connected_mnist',\n",
    "    [helper.make_tensor_value_info('X', TensorProto.FLOAT, ([-1, 784])),\n",
    "     helper.make_tensor_value_info('W1', TensorProto.FLOAT, W1_dims),\n",
    "     helper.make_tensor_value_info('W2', TensorProto.FLOAT, W2_dims),\n",
    "     helper.make_tensor_value_info('W3', TensorProto.FLOAT, W3_dims),\n",
    "     helper.make_tensor_value_info('B1', TensorProto.FLOAT, B1_dims),\n",
    "     helper.make_tensor_value_info('B2', TensorProto.FLOAT, B2_dims),\n",
    "     helper.make_tensor_value_info('B3', TensorProto.FLOAT, B3_dims),\n",
    "    ],\n",
    "    [helper.make_tensor_value_info('predictions', TensorProto.FLOAT, ([-1, 10]))],\n",
    "    [W1, W2, W3, B1, B2, B3]\n",
    ")\n",
    "original_model = helper.make_model(graph, producer_name='onnx-examples')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "onnx.checker.check_model(original_model)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "inferred_model = shape_inference.infer_shapes(original_model)\n",
    "onnx.save_model(inferred_model, \"mnist_fc.onnx\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Inferencing session"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import onnxruntime as lotus\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sess = lotus.InferenceSession('mnist_fc_model_with_cost.onnx', None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_dims = [1, 784]\n",
    "\n",
    "data = np.random.uniform(size=X_dims).astype(np.float32)\n",
    "labels = np.zeros(10).astype(np.float32)\n",
    "labels[3] = 1\n",
    "\n",
    "result = sess.run(['predictions', 'loss'], {'X': data, 'labels': labels})\n",
    "\n",
    "print(result[0])\n",
    "\n",
    "print(result[1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
